<template>
  <div>
    <el-upload
      v-bind="{ ...item }"
      :action="item!.action"
      :before-upload="newBeforeUpload"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :on-progress="handleProgress"
      :on-error="handleError"
      list-type="picture-card"
    >
      <el-icon>
        <ele-Plus />
      </el-icon>
    </el-upload>
    <el-image-viewer
      v-if="showViewer"
      :z-index="9999"
      @close="handleCloseImageViewer"
      :initial-index="showImageIndex"
      :url-list="urlList"
    />
  </div>
</template>

<script setup name="TImageUpload" lang="ts">
import { computed, ref } from "vue";
import { formEmits, formItemProps } from "../hooks/useFormItemHook";
import { useUploadHook } from "@/views/formgen/components/FormItem/hooks/useUploadHook";
import Compressor from "compressorjs";

const props = defineProps({
  ...formItemProps
});

const emits = defineEmits(formEmits);

const { changeValue, fileList, beforeUpload, handleRemove, handleExceed, uploadSuccess, handleProgress, handleError } =
  useUploadHook(props, emits);

const showViewer = ref(false);
const showImageIndex = ref(0);

const urlList = computed(() => {
  return changeValue.value.map((item: any) => item.url);
});

const newBeforeUpload = (file: any) => {
  const success = beforeUpload(file);
  if (!success) {
    return false;
  }
  // 开启压缩了
  if (!props.item?.openConversion) {
    return true;
  }
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: props.item?.conversionRatio || 0.8,
      // The compression process is asynchronous,
      // which means you have to access the `result` in the `success` hook function.
      success(result) {
        // result is a base64 encoded string
        // 压缩成功后返回压缩后的文件
        resolve(result);
      },
      error(err) {
        console.log("压缩失败" + err);
        resolve(file);
      }
    });
  });
};

const handlePictureCardPreview = (file: any) => {
  // 数据回显时结构不同
  let url = file.response && file.response.data;
  if (!url) {
    url = file.url;
  }
  // 找到下标
  showImageIndex.value = changeValue.value.findIndex((item: any) => item.url === url);
  showViewer.value = true;
};

// 关闭图片预览
const handleCloseImageViewer = () => {
  showViewer.value = false;
};
</script>
